/**
 * Copyright 2012 Alfredo "Rainbowbreeze" Morresi
 * 
 * This file is part of Apps4Italy PM10 project.
 * 
 * PM10 is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * PM10 is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with Foobar. If not, see http://www.gnu.org/licenses/.
 */
package it.rainbowbreeze.eureka.common;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import android.location.LocationListener;

/**
 * Registers all listeners to advice when location changes
 * 
 * @author Alfredo "Rainbowbreeze" Morresi
 */
public class LocationListenerQueue {
    // ------------------------------------------ Private Fields
    private static final String LOG_HASH = LocationListenerQueue.class.getSimpleName();
    private final LogFacility mLogFacility;
    private final HashMap<Class, WeakReference<LocationListener>> mListeners;

    // -------------------------------------------- Constructors
    public LocationListenerQueue(LogFacility logFacility) {
        mLogFacility = logFacility;
        mListeners = new HashMap<Class, WeakReference<LocationListener>>();
    }

    // --------------------------------------- Public Properties

    // -------------------------------------------------- Events

    // ------------------------------------------ Public Methods
    /**
     * Adds a new listener to the queue
     * 
     * @param locationListener
     */
    public void putListener(LocationListener locationListener) {
        if (null == locationListener) return;
        Class listener = locationListener.getClass();
        mLogFacility.v(LOG_HASH, "Putting listener of type " + listener.getSimpleName() + " inside queue");
        WeakReference<LocationListener> ref = new WeakReference<LocationListener>(locationListener);
        mListeners.put(listener, ref);
    }
    
    /**
     * Get all the registered listeners
     * @return
     */
    public Collection<LocationListener> getAllListeners() {
        mLogFacility.v(LOG_HASH, "Queue has " + mListeners.size() + " listeners");
        Collection<WeakReference<LocationListener>> weakValues = mListeners.values();
        ArrayList<LocationListener> listeners = new ArrayList<LocationListener>();
        for (WeakReference<LocationListener> weak : weakValues) {
            listeners.add(weak.get());
        }
        return listeners;
    }

    // ----------------------------------------- Private Methods
}
